﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Navigant.Infrastructure.Cases;
using Navigant.Infrastructure.EntityFactoryFramework;
using Navigant.Infrastructure.RepositoryFramework;
using Navigant.Model.PreservationNotices;

namespace Navigant.Infrastructure.Repositories
{
    public class SqlPreservationNoticeBatchRepository 
        : RepositoryBase<PreservationNoticeBatch>, IPreservationNoticeBatchRepository
    {
        #region Private Fields

        private ICase currentCase;
        private string connectionString;
        private IEntityFactory<PreservationNoticeBatch> entityFactory;

        #endregion

        #region Public Constructors

        public SqlPreservationNoticeBatchRepository(ICase currentCase)
            : this(currentCase, null)
        {
        }

        public SqlPreservationNoticeBatchRepository(ICase currentCase, IUnitOfWork unitOfWork)
            : base(unitOfWork)
        {
            this.currentCase = currentCase;
            this.connectionString = ConfigurationManager.ConnectionStrings["NavigantPortal"].ConnectionString;
            this.entityFactory = EntityFactoryBuilder.BuildFactory<PreservationNoticeBatch>();
        }

        #endregion

        #region Protected Methods

        protected override int PersistNewItem(PreservationNoticeBatch item)
        {
            if (item != null)
            {
                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {
                    using (SqlCommand command = new SqlCommand("SendNoticeQueueInsert",
                               connection))
                    {
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@SiteUrl", string.Empty); 
                        command.Parameters.AddWithValue("@NoticeID", item.NoticeId);
                        command.Parameters.AddWithValue("@PreservationCriteria", item.Criteria);
                        command.Parameters.AddWithValue("@FromAddress", item.FromEmailAddress);
                        command.Parameters.AddWithValue("@Created", item.Created);
                        command.Parameters.AddWithValue("@ExtraCriteriaName", item.ExtraCriteriaName == null ? "" : item.ExtraCriteriaName);
                        command.Parameters.AddWithValue("@ExtraCriteriaValue", item.ExtraCriteriaValue == null ? "" : item.ExtraCriteriaValue);
                        command.Parameters.AddWithValue("@NewSiteUrl", item.ParentCase.SiteAddress.AbsoluteUri);
                        command.Parameters.AddWithValue("@NewSiteID", item.ParentCase.Id); 
                        connection.Open();
                        command.ExecuteNonQuery();
                    }
                }
            }
            return 0;
        }

        protected override void PersistUpdatedItem(PreservationNoticeBatch item)
        {
            throw new NotImplementedException();
        }

        protected override void PersistDeletedItem(PreservationNoticeBatch item)
        {
            using (SqlConnection connection = new SqlConnection(this.connectionString))
            {
                using (SqlCommand command = new SqlCommand("SendNoticeQueueDelete", 
                    connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@SendNoticeQueueID", item.Id);
                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }

        #endregion

        #region IPreservationNoticeBatchRepository Members

        public override PreservationNoticeBatch FindBy(object key)
        {
            throw new NotImplementedException();
        }

        public override IList<PreservationNoticeBatch> FindAll()
        {
            throw new NotImplementedException();
        }

        public PreservationNoticeBatch FindNext()
        {
            PreservationNoticeBatch batch = null;
            using (SqlConnection connection = new SqlConnection(this.connectionString))
            {
                using (SqlCommand command = new SqlCommand("SendNoticeQueueGetOneNewSite",
                           connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@NewSiteID", this.currentCase.Id);
                    connection.Open();
                    using (IDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        if (reader.Read())
                        {
                            batch = this.entityFactory.BuildEntity(reader, this.currentCase);
                        }
                    }
                }
            }
            return batch;
        }

        public void AddToBatchHistory(PreservationNoticeBatch batch,
            PreservationNoticeBatchProcessStatus status,
            string errorMessage)
        {
            using (SqlConnection connection = new SqlConnection(this.connectionString))
            {
                using (SqlCommand command = new SqlCommand("SendNoticeHistoryInsert"))
                {
                    command.Connection = connection;
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@SendNoticeQueueID", batch.Key);
                    command.Parameters.AddWithValue("@SendNoticeStatusID", status);
                    command.Parameters.AddWithValue("@ErrorMessage", errorMessage);
                    command.Parameters.AddWithValue("@SiteUrl", string.Empty);
                    command.Parameters.AddWithValue("@NoticeID", batch.NoticeId);
                    command.Parameters.AddWithValue("@PreservationCriteria", batch.Criteria);
                    command.Parameters.AddWithValue("@FromAddress", batch.FromEmailAddress);
                    command.Parameters.AddWithValue("@SendNoticeCreated", batch.Created);
                    command.Parameters.AddWithValue("@NewSiteUrl", batch.ParentCase.SiteAddress.AbsoluteUri);
                    connection.Open();
                    command.ExecuteNonQuery();
                }
            }
        }

        #endregion
    }
}
